<template>
    <div class="ranking-container">
        <h2>积分排行</h2>
        <!-- 搜索区域 -->
        <div class="search-area">
            <div class="search-item">
                <span class="label">群:</span>
                <el-select v-model="selectedGroupId" placeholder="请选择群组" class="search-input" clearable
                    @change="handleGroupChange">
                    <div v-if="groupList.length === 0" class="el-select-dropdown__item">加载群组中...</div>
                    <el-option v-for="group in groupList" :key="group.groupId" :label="group.name || group.title"
                        :value="group.groupId" />
                </el-select>
            </div>
            <div class="search-item">
                <span class="label">群员昵称:</span>
                <el-input v-model="searchForm.nickname" placeholder="请输入群员昵称" class="search-input" clearable />
            </div>
            <div class="search-item">
                <span class="label">群员用户名:</span>
                <el-input v-model="searchForm.username" placeholder="请输入群员用户名" class="search-input" clearable />
            </div>
            <div class="search-item">
                <span class="label">群员id:</span>
                <el-input v-model="searchForm.userId" placeholder="请输入群员id" class="search-input" clearable />
            </div>
            <el-button type="primary" :icon="Search" class="search-btn" @click="handleSearch"
                :loading="loading">查找</el-button>
        </div>

        <!-- 表格区域 -->
        <el-table :data="rankingList" style="width: 100%" @selection-change="handleSelectionChange"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'normal' }" v-loading="loading">
            <el-table-column type="selection" width="45" />
            <el-table-column prop="group" label="群" min-width="150">
                <template #default="scope">
                    <span>{{ scope.row.group || getGroupName(scope.row.groupId) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="nickname" label="群员" min-width="150" />
            <el-table-column prop="username" label="群员用户名" min-width="150" />
            <el-table-column prop="userId" label="群员id" min-width="120" />
            <el-table-column prop="points" label="积分" width="100" align="center" sortable>
                <template #default="scope">
                    <span class="points">¥{{ scope.row.points }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="role" label="角色" width="100" align="center">
                <template #default="scope">
                    <el-tag :type="getRoleType(scope.row.role)" class="role-tag">
                        {{ getRoleName(scope.row.role) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150" align="center">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="handleAdjust(scope.row)">
                        调整积分
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container" v-if="total > 0">
            <span class="total-text">共 {{ total }} 条</span>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 50, 100]"
                layout="prev, pager, next, sizes" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" background class="custom-pagination" />
        </div>

        <!-- 无数据提示 -->
        <div class="no-data" v-if="total === 0 && !loading">
            <el-empty description="暂无积分排行数据" />
        </div>

        <!-- 调整积分弹窗 -->
        <el-dialog v-model="adjustDialogVisible" title="调整积分" width="500px">
            <div class="adjust-form">
                <div class="form-item">
                    <span class="label">群员:</span>
                    <span>{{ selectedMember.nickname }}</span>
                </div>
                <div class="form-item">
                    <span class="label">当前积分:</span>
                    <span>¥{{ selectedMember.points }}</span>
                </div>
                <div class="form-item">
                    <span class="label">调整积分:</span>
                    <el-input-number v-model="adjustForm.points" :min="-1000" :max="1000" />
                </div>
                <div class="form-item">
                    <span class="label">原因:</span>
                    <el-input v-model="adjustForm.reason" placeholder="请输入调整原因" />
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="adjustDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAdjust" :loading="adjustLoading">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getPointsRanking, adjustPoints } from '@/api/points'
import { getGroupList } from '@/api/group'

export default {
    name: 'Ranking',
    setup() {
        // 搜索表单
        const searchForm = reactive({
            nickname: '',
            username: '',
            userId: ''
        });

        const selectedGroupId = ref('');
        const rankingList = ref([]);
        const groupList = ref([]);
        const loading = ref(false);
        const currentPage = ref(1);
        const pageSize = ref(20);
        const total = ref(0);

        // 调整积分相关
        const adjustDialogVisible = ref(false);
        const adjustLoading = ref(false);
        const selectedMember = ref({});
        const adjustForm = reactive({
            points: 0,
            reason: ''
        });

        // 获取群组列表
        const fetchGroups = async () => {
            try {
                console.log('开始获取群组列表...');
                const response = await getGroupList();
                console.log('群组列表原始响应:', response);

                if (response && response.data) {
                    // 检查返回数据结构
                    if (Array.isArray(response.data)) {
                        groupList.value = response.data;
                        console.log('群组列表加载成功(数组):', groupList.value.length, '个群组');
                    } else if (response.data.data && Array.isArray(response.data.data)) {
                        // 如果数据嵌套在data字段中
                        groupList.value = response.data.data;
                        console.log('群组列表加载成功(嵌套):', groupList.value.length, '个群组');
                    } else if (typeof response.data === 'object') {
                        // 如果返回的是对象而非数组，尝试转换
                        const groups = [];
                        for (const key in response.data) {
                            if (Object.prototype.hasOwnProperty.call(response.data, key)) {
                                const group = response.data[key];
                                if (group.groupId) {
                                    groups.push(group);
                                }
                            }
                        }
                        groupList.value = groups;
                        console.log('群组列表加载成功(对象转换):', groupList.value.length, '个群组');
                    } else {
                        console.warn('群组数据结构异常:', response.data);
                        groupList.value = [];
                    }
                } else {
                    console.warn('获取群组列表失败: 响应为空');
                    groupList.value = [];
                }

                // 如果有群组，默认选择第一个
                if (groupList.value.length > 0 && !selectedGroupId.value) {
                    selectedGroupId.value = groupList.value[0].groupId;
                    fetchRanking();
                }
            } catch (error) {
                console.error('获取群组列表失败:', error);
                ElMessage.error('获取群组列表失败');
                groupList.value = [];
            }
        };

        // 获取积分排行
        const fetchRanking = async () => {
            if (!selectedGroupId.value) {
                rankingList.value = [];
                total.value = 0;
                return;
            }

            loading.value = true;
            try {
                const params = {
                    page: currentPage.value,
                    limit: pageSize.value,
                    ...searchForm
                };

                console.log('获取积分排行参数:', selectedGroupId.value, params);
                const response = await getPointsRanking(selectedGroupId.value, params);
                console.log('获取到的积分排行数据:', response);

                // 访问嵌套数据结构
                if (response && response.data && response.data.success) {
                    rankingList.value = response.data.data || [];
                    const pagination = response.data.pagination || {};
                    total.value = pagination.total || 0;
                } else {
                    console.warn('响应数据结构不符合预期:', response);
                    rankingList.value = [];
                    total.value = 0;
                }
            } catch (error) {
                console.error('获取积分排行失败:', error);
                if (error.response && error.response.data && error.response.data.message) {
                    ElMessage.error(error.response.data.message);
                } else {
                    ElMessage.error('获取积分排行失败，请稍后重试');
                }
                rankingList.value = [];
                total.value = 0;
            } finally {
                loading.value = false;
            }
        };

        // 群组变更
        const handleGroupChange = () => {
            currentPage.value = 1; // 重置为第一页
            fetchRanking();
        };

        // 搜索
        const handleSearch = () => {
            currentPage.value = 1; // 重置为第一页
            fetchRanking();
        };

        const handleSelectionChange = (selection) => {
            console.log('选中的行:', selection);
        };

        const handleSizeChange = (val) => {
            pageSize.value = val;
            fetchRanking();
        };

        const handleCurrentChange = (val) => {
            currentPage.value = val;
            fetchRanking();
        };

        // 根据群组ID查找群组名称
        const getGroupName = (groupId) => {
            if (!groupId) return '未知群组';
            const group = groupList.value.find(g => g.groupId === groupId);
            return group ? (group.name || group.title || group.groupName) : '未知群组';
        };

        // 获取角色类型（颜色）
        const getRoleType = (role) => {
            switch (role) {
                case 'creator': return 'danger';
                case 'administrator': return 'warning';
                case 'member': return '';
                default: return 'info';
            }
        };

        // 获取角色名称
        const getRoleName = (role) => {
            switch (role) {
                case 'creator': return '群主';
                case 'administrator': return '管理员';
                case 'member': return '成员';
                default: return '未知';
            }
        };

        // 调整积分
        const handleAdjust = (row) => {
            selectedMember.value = { ...row };
            adjustForm.points = 0;
            adjustForm.reason = '';
            adjustDialogVisible.value = true;
        };

        // 确认调整积分
        const confirmAdjust = async () => {
            if (!adjustForm.points) {
                ElMessage.warning('请输入调整积分');
                return;
            }

            adjustLoading.value = true;
            try {
                const data = {
                    groupId: selectedMember.value.groupId,
                    userId: selectedMember.value.userId,
                    points: adjustForm.points,
                    reason: adjustForm.reason || '管理员调整'
                };

                const response = await adjustPoints(data);
                console.log('调整积分响应:', response);

                if (response && response.data && response.data.success) {
                    ElMessage.success('积分调整成功');
                    adjustDialogVisible.value = false;
                    fetchRanking(); // 刷新数据
                } else {
                    ElMessage.error(response?.data?.message || '积分调整失败');
                }
            } catch (error) {
                console.error('调整积分失败:', error);
                ElMessage.error(error.response?.data?.message || '调整积分失败，请稍后重试');
            } finally {
                adjustLoading.value = false;
            }
        };

        onMounted(() => {
            fetchGroups();
        });

        return {
            searchForm,
            selectedGroupId,
            rankingList,
            groupList,
            currentPage,
            pageSize,
            total,
            loading,
            adjustDialogVisible,
            adjustLoading,
            selectedMember,
            adjustForm,
            Search,
            handleGroupChange,
            handleSearch,
            handleSelectionChange,
            handleSizeChange,
            handleCurrentChange,
            getGroupName,
            getRoleType,
            getRoleName,
            handleAdjust,
            confirmAdjust
        };
    }
}
</script>

<style scoped>
.ranking-container {
    background-color: #fff;
    border-radius: 2px;
    padding: 15px;
}

.search-area {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 15px;
    flex-wrap: wrap;
}

.search-item {
    display: flex;
    align-items: center;
}

.label {
    font-size: 13px;
    color: #606266;
    margin-right: 8px;
}

.search-input {
    width: 180px;
}

.search-btn {
    height: 32px;
    padding: 0 15px;
    font-size: 13px;
}

.points {
    font-weight: 500;
    color: #67C23A;
}

.adjust-form {
    padding: 0 20px;
}

.form-item {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
}

.form-item .label {
    width: 80px;
}

.pagination-container {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.total-text {
    margin-right: 12px;
    color: #606266;
    font-size: 13px;
}

:deep(.el-table) {
    --el-table-border-color: #ebeef5;
    font-size: 13px;
}

:deep(.el-table th) {
    font-weight: normal;
    height: 40px;
    padding: 8px 0;
}

:deep(.el-table td) {
    padding: 8px 0;
}

:deep(.role-tag) {
    height: 22px;
    padding: 0 8px;
    font-size: 12px;
}

:deep(.el-pagination) {
    font-size: 13px;
}

:deep(.el-pagination .el-select .el-input) {
    width: 100px;
}

:deep(.el-pagination button) {
    min-width: 28px;
    height: 28px;
}

:deep(.el-pagination .el-select .el-input__inner) {
    height: 28px;
}

:deep(.el-button--primary) {
    --el-button-bg-color: #1890ff;
    --el-button-border-color: #1890ff;
    --el-button-hover-bg-color: #40a9ff;
    --el-button-hover-border-color: #40a9ff;
}

:deep(.el-input__inner) {
    height: 32px;
}

:deep(.el-select__caret) {
    height: 32px;
    line-height: 32px;
}
</style>